package com.neusoft.ysu.populationmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neusoft.ysu.populationmanagement.constant.TabelDic;
import com.neusoft.ysu.populationmanagement.entity.CommonResult;
import com.neusoft.ysu.populationmanagement.entity.Household;
import com.neusoft.ysu.populationmanagement.mapper.HouseholdMapper;
import com.neusoft.ysu.populationmanagement.service.IHouseholdService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzh
 * @since 2025-06-13
 */
@Service
public class HouseholdServiceImpl  implements IHouseholdService {

    @Autowired
    HouseholdMapper householdMapper;

    /**
     * @author zyk
     * @date 2025-06-13
     * @param
     * @return com.neusoft.ysu.populationmanagement.entity.CommonResult
     */
    @Override
    public CommonResult selectLastInfo() {
        LambdaQueryWrapper<Household> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //等效sql: select * from household order by housenum desc limit 1
        lambdaQueryWrapper.orderByDesc(Household::getHousenum).last("limit 1");
        List<Household> households = householdMapper.selectList(lambdaQueryWrapper);
        if (households.size()<=0){
            if (householdMapper.selectCount(null)!=0){
                return new CommonResult<>(0,"户号信息错误请联系管理员",null);
            }
            //如果是第一户返回000000001
            return new CommonResult<>(1,"户号","000000001");
        }
        String lastHouseNum = households.get(0).getHousenum();
        String newHouseNum = String.format("%09d",(Integer.parseInt(lastHouseNum)+1)); //不满九位填充满九位，一直加1
        return new CommonResult<>(1,"户号",newHouseNum);
    }

    /**
     * @author zyk
     * @date 2025-06-13
     * @param household
     * @return CommonResult:1代表成功，0代表失败
     */

    @Override
    public CommonResult insertHousehold(Household household) {
        household.setCreateTime(LocalDateTime.now());
        household.setSetdate(LocalDate.now());
        household.setIsDelete(TabelDic.IS_DELETE_NO);
        int rows = householdMapper.insert(household);
        if (rows<=0){
            return new CommonResult<>(0,"插入户口失败",null);
        }
        return new CommonResult<>(1,"插入户口成功",null);
    }
}
